package cn.com.dealme.nutz.validation;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;

import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.view.UTF8JsonView;

import cn.com.dealme.error.ErrorMap;

public class ValidateFailDispatcher {

	private static final Log log = Logs.getLog(ValidateFailDispatcher.class);

	private String failView;

	public ValidateFailDispatcher(String failView) {
		this.failView = failView;
	}

	public void dispatch(ActionContext ac, Map<String, String> errMap) throws IOException, ServletException {
		if (failView == null) {
			new UTF8JsonView(JsonFormat.compact()).render(ac.getRequest(), ac.getResponse(), errMap);
			if(log.isDebugEnabled()) {
				log.debug("write text : \n" + Json.toJson(errMap, JsonFormat.compact()));
			}
		} else {
			ac.getRequest().setAttribute(ErrorMap.ERR_MAP_KEY,
					errMap);
			ac.getRequest().getRequestDispatcher(failView).forward(
					ac.getRequest(), ac.getResponse());
		}
	}
}
